const App = getApp();
import { url } from '../../../../../modelApi/url_config.js'
Page({
    data: {
        statusBarHeight: "",
        statusBarPadding: "",
        addressData: null, //收货地址
        orderSettlementData: {}, //订单信息
        addressId: "", //地址id
        out_trade_no: '',
        couponId: "", //优惠券id
        couponAmount: "", //优惠券金额
        remark: "", //备注
        clickShowShops: false, //是否显示弹窗内容
        showShopsOpen: false, //显示弹窗或关闭弹窗的操作动画
        allMoney: "", // 总计金额
    },
    onLoad: function (a) {
        let orderSettlementData = wx.getStorageSync('orderSettlementData') || {};
        let couponId = "",
            couponAmount = "";
        orderSettlementData.couponSet.length > 0 && orderSettlementData.couponSet.forEach((element, index) => {
            if (index === 0) {
                element.selected = true;
                couponId = element.couponId
                couponAmount = element.amount
            } else {
                element.selected = false
            }
        });
        this.setData({
            statusBarPadding: App.globalData.navTop,
            statusBarHeight: App.globalData.navHeight,
            orderSettlementData: orderSettlementData,
            couponId: couponId,
            couponAmount: couponAmount,
            allMoney: this.minus(orderSettlementData.payableMoney, couponAmount)
        });
    },
    onShow: function () {
        if (this.data.addressId) {
            this.getchoiseAdrressFun();
        } else {
            this.getdefaultAdrressFun(); // 获取默认地址
        }
    },
    /* 弹出优惠券列表 */
    goCouponList: function () {
        let _that = this;
        if (!_that.data.clickShowShops) {
            _that.setData({
                clickShowShops: true,
            })
        }

        if (_that.data.showShopsOpen) {
            _that.setData({
                showShopsOpen: false,
            })

            // 关闭显示弹窗动画的内容，不设置的话会出现：点击任何地方都会出现弹窗，就不是指定位置点击出现弹窗了
            setTimeout(() => {
                _that.setData({
                    clickShowShops: false,
                })
            }, 500)


        } else {
            _that.setData({
                showShopsOpen: true
            })
        }
        return
        wx.navigateTo({
            url: "/pages/mine/sonpages/couponList/index"
        });
    },
    /* 选择优惠券 */
    selectFun: function (e) {
        let indexData = e.currentTarget.dataset.index;
        let orderSetData = this.data.orderSettlementData;
        if (orderSetData.couponSet[indexData].selected) {
            orderSetData.couponSet[indexData].selected = false;
            this.setData({
                orderSettlementData: orderSetData
            });
            return;
        }
        orderSetData.couponSet.forEach(element => {
            element.selected = false
        });
        orderSetData.couponSet[indexData].selected = true
        this.setData({
            orderSettlementData: orderSetData
        })
    },
    /* 确定优惠券 */
    sureCouponFun() {
        let choiseCouponId = "",
            choiseCouponAmount = "";
        let orderSetData = this.data.orderSettlementData;
        orderSetData.couponSet.forEach(element => {
            if (element.selected) {
                choiseCouponId = element.couponId;
                choiseCouponAmount = element.amount;
            }
        });
        this.setData({
            couponId: choiseCouponId,
            couponAmount: choiseCouponAmount,
            allMoney: this.minus(this.data.orderSettlementData.payableMoney, choiseCouponAmount)
        });
        this.goCouponList();
    },
    /* 获取备注 */
    phoneInput: function (e) {
        this.setData({
            remark: e.detail.value,
        })
    },
    /* 提交订单 */
    gopay: function () {
        if (!this.data.addressId) {
            wx.showToast({
                icon: 'none',
                title: '请选择收货地址！',
            })
            return
        }
        let params = {
            orderByCart: "1",
            orderDetail: JSON.stringify(wx.getStorageSync('orderSettlementData').orderDetail),
            receiverAddressId: this.data.addressId,
            couponId: this.data.couponId,
            promoterId: wx.getStorageSync('shareUserId') ? wx.getStorageSync('shareUserId') : "",
            remark: this.data.remark
        }
        App.ajax(url.orderSubmitUrl, params, 'post').then(res => {
            if (res.code == 0) {
                this.WXPay(res.data.orderId)
            }
        })
    },
    /* 跳转地址列表 */
    goAddressList: function () {
        if (this.data.addressId) {
            wx.navigateTo({
                url: "/pages/address/index?addressId=" + this.data.addressId
            });
        } else {
            wx.navigateTo({
                url: "/pages/address/index"
            });
        }
    },
    /* 获取默认地址 */
    getdefaultAdrressFun() {
        App.ajax(url.defaultAdrressUrl, {}, 'get').then(res => {
            if (+res.code === 0 && res.data) {
                this.setData({
                    addressData: res.data,
                    addressId: res.data.id
                })
            }
        })
    },
    /* 获取选中地址 */
    getchoiseAdrressFun() {
        App.ajax(url.addressDetailUrl, { 'addressId': this.data.addressId }, 'get').then(res => {
            this.setData({
                addressData: res.data,
                addressId: res.data.id
            })
        })
    },
    getaddrpageAddr(id) {
        this.setData({
            addressId: id
        })
    },
    /* 微信支付 */
    WXPay: function (orderId) {
        const that = this;
        let params = {
            openId: wx.getStorageSync('openId'),
            orderId: orderId
        }
        App.ajax(url.wxapiPayUrl, params, 'post').then(res => {
            if (res.code === 0 && res.data) {
                that.setData({
                    out_trade_no: res.data.out_trade_no
                })
                wx.requestPayment({
                    'timeStamp': res.data.timeStamp,
                    'nonceStr': res.data.nonceStr,
                    'package': res.data.package,
                    'signType': res.data.signType,
                    'paySign': res.data.paySign,
                    success: function (res1) {
                        that.getorderNo(that.data.out_trade_no);
                    },
                    fail: function (res1) {
                        wx.showToast({
                            title: '取消支付',
                            icon: 'none',
                            duration: 2000
                        })
                    }
                })
            }
        })
    },
    // 获取轮循订单号
    getorderNo(data) {
        const param = { orderNo: data }
        App.ajax(url.getByNo, param, 'get').then(res => {
            const data = res.data;
            if (+res.code === 0 && data) {
                if (+data.payStatus === 1) {
                    wx.reLaunch({
                        url: `/pages/orderDetail/index?orderId=${data.orderId}`,
                    })
                    return;
                }
                this.getorderNo(this.data.out_trade_no)
            }
        })
    },
    /* 减法 */
    minus: function(num1, num2) {
        var c, d, e;
        try {
            c = num1.toString().split(".")[1].length;
        } catch (err) {
            c = 0;
        }
        try {
            d = num2.toString().split(".")[1].length;
        } catch (err) {
            d = 0;
        }
        return e = Math.pow(10, Math.max(c, d)), (this.mul(num1, e) - this.mul(num2, e)) / e;
    },
    mul: function(a, b) {
        var c = 0,
            d = a.toString(),
            e = b.toString();
        try {
            c += d.split(".")[1].length;
        } catch (f) {}
        try {
            c += e.split(".")[1].length;
        } catch (f) {}
        return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
    }
})